package homework.billing.meter.simple;

import homework.billing.meter.Meter;

public class LadderMeter implements Meter {

    protected float[][] ladderChain;
    private int ladderLen = 0;

    public LadderMeter() {
        ladderChain = new float[10][2];
    }

    public int getLadderCount() {
        return ladderLen;
    }

    public int addLadder(float a, float price) {
        if(ladderLen == 0 && a != 0)
            addLadder(0, 0);
        else if(ladderLen > 0 && ladderChain[ladderLen-1][0] > a)
            // XXX: raise exception
            return ladderLen;

        ladderChain[ladderLen][0] = a;
        ladderChain[ladderLen][1] = price;
        return ++ladderLen;
    }

    public double ladderCost(float value) {
        double result = 0;
        float level, price, distance;
        for(int i=0;i<getLadderCount();i++) {
            level = ladderChain[i][0];
            price = ladderChain[i][1];

            // 防止nextLevel越界
            if(i == ladderLen - 1) {
                result += value * price;
                break;
            }

            distance = ladderChain[i+1][0] - level;
            if(value < distance) {
                result += value * price;
                break;
            } else {
                result += distance * price;
                value -= distance;
            }
        }
        return result;
    }

    @Override
    public double cost(float param) {
        return ladderCost(param);
    }
}
